package www.study.com;

//两数相加 https://leetcode.cn/problems/add-two-numbers/submissions/
public class code2 {
    public static void main(String[] args) {

    }
    class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode res = new ListNode();
            ListNode pre = res;
            int up = 0; //进位
            int addX = 0;
            int addY = 0;
            int sum = 0;
            while (l1 != null || l2 != null){
                addX = l1 != null ? l1.val : 0;
                addY = l2 != null ? l2.val : 0;
                l1 = l1 != null ? l1.next : l1;
                l2 = l2 != null ? l2.next : l2;
                sum = addX + addY + up;
                pre.next = new ListNode(sum % 10);
                pre = pre.next;
                up = sum / 10;
            }
            while (up != 0){
                pre.next = new ListNode(up % 10);
                pre = pre.next;
                up = up / 10;
            }
            pre = res.next;
            res.next = null;
            return pre;
        }
    }
}
